package br.org.imazon.sad;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import javax.servlet.http.*;

import com.google.gdata.util.AuthenticationException;
import com.google.gdata.util.ServiceException;
import com.google.gson.Gson;

@SuppressWarnings("serial")
public class ChoosePolyServlet extends HttpServlet {
	
	private static final String SERVICE_URL =
	    "http://www.google.com/fusiontables/api/query";
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		
	  
		try {
			
			HttpSession session = req.getSession();
			String auth = Authenticate.auth(session,"fusiontables");
		
			if ((req.getParameter("table") != null) && (req.getParameter("row") != null)) {
			     //ArrayList<HashMap<String,String>> polygons = (ArrayList<HashMap<String,String>>) session.getAttribute("polygonNames");
			     //HashMap<String,String> thisPolygon = polygons.get(Integer.parseInt(req.getParameter("polygon")));
			     //String thisTable = thisPolygon.get("table_id");
			     //String thisRow = thisPolygon.get("name");
			     String thisTable = req.getParameter("table");
			     String thisRow = req.getParameter("row");
			     System.out.println("in choose poly, table is " +thisTable + " row is " + thisRow);
			     FusionTablesAccess access = new FusionTablesAccess(auth);
		 	     String kml = access.getKML(thisTable, thisRow);
		 	     System.out.println(kml);
			   
		 	    resp.setCharacterEncoding("UTF-8");
		      resp.getWriter().print((new Gson()).toJson(kml)); 	
			} else {
				resp.sendRedirect("/index.jsp");
			}
		} catch (AuthenticationException e) {
		  resp.setStatus(403);
		} catch (ServiceException e) {
			resp.setStatus(500);
      resp.getOutputStream().print(e.getMessage());
		}
	}
}
